package cn.bdqn.util;

import cn.bdqn.entity.Staff;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static final String SECRET="Ksk34@4kqkj34&3hsoqlsdfjj";
    public static String createToken(Staff staff) {
        //添加构成JWT的参数
        Map<String, Object> headMap = new HashMap();
        headMap.put("alg", SignatureAlgorithm.HS256.getValue());//使用HS256签名算法
        headMap.put("typ", "JWT");

        Map body = new HashMap();
        body.put("userId",staff.getStaffId());
        body.put("username",staff.getUsername());
        body.put("role","admin");

        DateTime now = DateTime.now();
        DateTime offset = DateUtil.offset(now, DateField.DAY_OF_MONTH, 2);

        String jwt = Jwts.builder()
                .setHeader(headMap)
                .setClaims(body)
                .signWith(SignatureAlgorithm.HS256,SECRET)
                .setExpiration(offset)
                .compact();
        System.out.println(jwt);

        return jwt;

    }

    public static Object parseJwt(String token){
        //解析jwt
        Jwt result = Jwts.parser().setSigningKey(SECRET).parse(token);
        Object jwtBody = result.getBody();
//        Header header = result.getHeader();
        return jwtBody;
    }
}
